//
//  EmoticonView.swift
//  表情键盘
//
//  Created by 小小罗 on 15/11/16.
//  Copyright © 2015年 RealMadrid. All rights reserved.
//

import UIKit

// 可重用 Cell Id
private let EmoticonViewCellId = "EmoticonViewCellId"

// MARK: 表情键盘视图
class EmoticonView: UIView {

    //选中表情回调
    private var selectedEmoticonCallBack:(emoticon: Emoticon)->()
    
    // MARK: - 监听方法
    @objc private func clickItem(item: UIBarButtonItem) {
        print("选中的分类\(item.tag)")
        
        let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
        
        // 滚动 collectionView
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: true)
    
    }
    
   // MARK: - 构造函数
     init(selectedEmoticon:(emoticon: Emoticon)->()) {
        
        //记录闭包属性
        self.selectedEmoticonCallBack = selectedEmoticon
        
        // 调用父类的构造函数
        var rect = UIScreen.mainScreen().bounds
        rect.size.height = 226
        super.init(frame: rect)
        backgroundColor = UIColor.greenColor()
        
        setUpUI()
        //让一出现就显示默认表情
        let indexpath = NSIndexPath(forItem: 0, inSection: 1)
        //添加到主队列 等待主线程上的代码执行完再执行
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            
            self.collectionView.scrollToItemAtIndexPath(indexpath, atScrollPosition: .Left, animated: false)
            
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    //MARK: -懒加载控件
    private lazy var collectionView : UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: EmoticonLayout())
    private lazy var toolBar : UIToolbar = UIToolbar()
    //表情包数组
    private lazy var packages = EmoticonManger.sharedManager.packages
    
    // MARK: - 表情布局(类中类－只允许被包含的类使用)
    private class EmoticonLayout : UICollectionViewFlowLayout {
    
        private override func prepareLayout() {
            super.prepareLayout()
            
            let col: CGFloat = 7
            let row: CGFloat = 3
            
            let w = collectionView!.bounds.width / col
            // 如果在 iPhone 4 的屏幕，只能显示两行 所以这里要乘以0.499 而不是0.5
            let margin = (collectionView!.bounds.height - row * w) * 0.499
            
            itemSize = CGSize(width: w, height: w)
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
            
            scrollDirection = .Horizontal
            
            collectionView?.pagingEnabled = true
            collectionView?.bounces = false
            collectionView?.showsHorizontalScrollIndicator = false

            
        }
    
    }
    
}


//MARK: -设置界面
// private 修饰的 extension 内部的所有函数都是私有的
private extension EmoticonView {
    
    func setUpUI() {
        //1.添加子控件
        addSubview(collectionView)
        addSubview(toolBar)
        
        //2.设置布局
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(self.snp_bottom)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
            make.height.equalTo(44)
        }
        
        collectionView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_top)
            make.bottom.equalTo(toolBar.snp_top)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)

        }
        
        //3.准备控件
        prepareToolBar()
        prepareCollectioinView()
    
    }
    
    //准备工具栏
    func prepareToolBar() {
    
        toolBar.tintColor = UIColor.darkGrayColor()
        
        //1.设置按钮内容
        var items = [UIBarButtonItem]()
        
        // toolbar 中，通常是一组功能相近的操作，只是操作的类型不同，通常利用 tag 来区分
        var index = 0
        for s in packages {
        
            items.append(UIBarButtonItem(title: s.group_name_cn, style: .Plain, target: self, action: "clickItem:"))
            
            items.last?.tag = index++
            //添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
        }
        
        //删除最后一个弹簧
        items.removeLast()
        
        toolBar.items = items
    
    }
    
    func prepareCollectioinView() {
        
        collectionView.backgroundColor = UIColor.lightGrayColor()
        
        //注册cell
        collectionView.registerClass(EmoticonViewCell.self, forCellWithReuseIdentifier: EmoticonViewCellId)
        
        //设置数据源
        collectionView.dataSource = self
        
        //设置代理
        collectionView.delegate = self
    
    }

}

//MARK : -UICollectionViewDataSource
extension EmoticonView : UICollectionViewDataSource,UICollectionViewDelegate {
    //MARK: -代理方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        //获取表情模型
        let m = packages[indexPath.section].emoticons[indexPath.item]
        
        //回调
        selectedEmoticonCallBack(emoticon: m)

        
    }
    
    //MARK: -数据源方法
    // 返回分组数量 － 表情包的数量
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
   // 返回每个表情包中的表情数量
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmoticonViewCellId, forIndexPath: indexPath) as! EmoticonViewCell
        
//        cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.greenColor() : UIColor.orangeColor()
        cell.emoticon = packages[indexPath.section].emoticons[indexPath.item]

        return cell
    }




}


//MARK : -自定义cell
private class EmoticonViewCell : UICollectionViewCell {

    //表情模型
    var emoticon: Emoticon? {
        didSet{
            emoticonButton.setImage(UIImage(contentsOfFile: emoticon!.imagePath), forState: UIControlState.Normal)
            emoticonButton.setTitle(emoticon?.emoji, forState: UIControlState.Normal)
            
            //设置删除按钮
            if emoticon!.isRemoved {
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
            }
            
            // 设置 emoji，千万不要加上判断，否则显示会不正常
            if emoticon?.emoji != nil {
            }
        
        }
    }
    
    
    //MARK : -构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.addSubview(emoticonButton)
        
        emoticonButton.backgroundColor = UIColor.whiteColor()
        emoticonButton.frame = CGRectInset(bounds, 4, 4)
        
        //字体的大小和高度相近
        emoticonButton.titleLabel?.font = UIFont.systemFontOfSize(32)
        
        emoticonButton.userInteractionEnabled = false
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    

    //MARK: - 懒加载控件
    private lazy var emoticonButton : UIButton = UIButton()
}























